<?php
class Wall_Api_Advcomment extends Core_Api_Abstract
{
  /**
   * Loader for parsers
   * 
   * @var Zend_Loader_PluginLoader
   */
  protected $_pluginLoader;
  
      const IMAGE_WIDTH = 720;
    const IMAGE_HEIGHT = 720;

    const THUMB_WIDTH = 140;
    const THUMB_HEIGHT = 160;


  
  
  public function createPhoto($params, $file)
    {
        if( $file instanceof Storage_Model_File )
        {
            $params['file_id'] = $file->getIdentity();
        }

        else
        {
            // Get image info and resize
            $name = basename($file['tmp_name']);
            $path = dirname($file['tmp_name']);
            $extension = ltrim(strrchr($file['name'], '.'), '.');

            $mainName = $path.'/m_'.$name . '.' . $extension;
            $thumbName = $path.'/t_'.$name . '.' . $extension;

            $image = Engine_Image::factory();
            $image->open($file['tmp_name'])
            ->resize(self::IMAGE_WIDTH, self::IMAGE_HEIGHT)
            ->write($mainName)
            ->destroy();

            $image = Engine_Image::factory();
            $image->open($file['tmp_name'])
            ->resize(self::THUMB_WIDTH, self::THUMB_HEIGHT)
            ->write($thumbName)
            ->destroy();

            // Store photos
            $photo_params = Array('parent_id'=>$params['owner_id'], 'parent_type'=>$params['owner_type']);

            try {
                $photoFile = Engine_Api::_()->storage()->create($mainName, $photo_params);
                $thumbFile = Engine_Api::_()->storage()->create($thumbName, $photo_params);
            }
            catch (Exception $e)
            {
                if ($e->getCode() == Storage_Api_Storage::SPACE_LIMIT_REACHED_CODE)
                {
                    echo $e->getMessage();
                    exit();
                }
            }

            $photoFile->bridge($thumbFile, 'thumb.normal');

            $params['file_id'] = $photoFile->file_id; // This might be wrong
            $params['photo_id'] = $photoFile->file_id;
        }

        // Remove temp files
        @unlink($mainName);
        @unlink($thumbName);


        return $params;

    }
}